<script lang="ts">
import { ref } from 'vue'
import { Delete, Download, Plus, ZoomIn, UploadFilled, User, SwitchButton } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type ComponentSize, type FormRules, type UploadFile } from 'element-plus'
import { createPostService } from '@/api/post.js'
import router from '@/router'
import { useTokenStore } from '@/stores/token'

// 表单数据和验证规则
const posts = ref({
  title: '',
  content: '',
  postType: '',
  coverImg:''
})

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const formSize = ref<ComponentSize>('default')

const rules: FormRules = {
  title: [
    { required: true, message: '请填写帖子标题', trigger: 'blur' },
    { min: 3, max: 15, message: '长度至少3到15个字符', trigger: 'blur' }
  ],
  postType: [
    { required: true, message: '请选择帖子类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' }
  ],
  coverImg: [
    { required: false, message: '附件', trigger: 'blur' }]
}

// 退出登录
const handleCommand = (command: string) => {
  if (command === 'logout') {
    ElMessageBox.confirm(
      '你确认退出登录吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async () => {
        try {
          const tokenStore = useTokenStore()
          tokenStore.removeToken()
          router.push('/login')
          localStorage.setItem('isLoggedIn', 'false')
        } catch (error) {
          console.error('发生错误：', error)
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消退出'
        })
      })
  }
}

// 表单提交
const submitForm = async function () {
  console.log('提交表单开始')

  const ruleForm = this.$refs.ruleFormRef // 通过 $refs 获取表单实例

  if (!ruleForm) {
    console.log('ruleFormRef 未绑定到表单实例')
    return
  }
  ruleForm.validate(async (valid) => {
    console.log('验证完成，验证结果:', valid)
    if (valid) {
      try {
        const result = await createPostService(posts.value)
        ElMessage.success(result.data ? result.data : '提交成功')
        console.log('数据提交成功')
        router.push('/community') // 假设这是提交成功后的跳转函数
        getCommunity() // 假设这是重新加载内容的函数
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请检查填写信息')
      }
    } else {
      console.log('表单验证失败')
      ElMessage.error('表单验证失败，请检查输入内容')
    }
  })
}

const getCommunity = () => {
  console.log('加载社区内容...')
}

const handleRemove = (file: UploadFile) => {
  console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}

export default {
  components: {
    Delete,
    Download,
    Plus,
    ZoomIn,
    UploadFilled,
    User,
    SwitchButton
  },
  data() {
    return {
      activeIndex: '2',
      searchQuery: '',
      isLoggedIn: false,
      userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      isDark: false,
      formSize,
      posts,
      rules,
      dialogImageUrl,
      dialogVisible,
      disabled,
      handleSelect: '',
      handlePictureCardPreview,
      handleRemove,
      handleDownload,
      handleCommand,
      User,
      SwitchButton
    }
  },
  methods: {
    submitForm, // 表单提交方法
    navigateTologin(page) {
      this.$router.push(`/${page}`) // 跳转到登录页面
    },
    navigateToregister(page) {
      this.$router.push(`/${page}`) // 跳转到注册页面
    },
    onError(event) {
      event.target.onerror = null // 避免无限循环
      event.target.src = 'images/default-icon.png' // 设置默认图标
    },
    setDefaultLogo() {
      this.logoSrc = 'src/assets/logo.jpg'
    },
    setDefaultIcon(event) {
      event.target.src = 'images/default-icon.png'
    },
    setDefaultAvatar(event) {
      event.target.src = 'images/default-avatar.jpg'
    },
    navigateTo(link) {
      window.location.href = link
    },
    search() {
      console.log('Searching for:', this.searchQuery)
    },
    goToDetails(service) {
      console.log('Going to details for:', service.title)
    }
  }
}
</script>

<template>
  <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false" @select="handleSelect"
           style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
    <el-menu-item index="0">
      <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg" alt="CodeCash" />
    </el-menu-item>
    <div index="1" style="transform: translate(-105%,15px);">
      <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
      <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
    </div>
    <div index="2" style="transform: translateX(-2%);">
      <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
      <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
      <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
      <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
      <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
    </div>
    <div index="3" style="transform: translateY(25%);margin-right: 20px;">
      <el-dropdown placement="bottom-end">
        <el-avatar :src="userAvatar" size="medium" />
        <el-icon><CaretBottom /></el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="userInfo" :icon="User" @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
            <el-dropdown-item command="logout" :icon="SwitchButton" @click="handleCommand('logout')">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-menu>

  <el-main style="max-width: 750px;border: 1px solid #ccc;padding: 20px;margin: 20px auto;">
    <h1 style="text-align: center;">发布帖子</h1>
    <el-form ref="ruleFormRef" :model="posts" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="帖子标题" prop="title">
        <el-input v-model="posts.title" placeholder="请填写帖子标题" />
      </el-form-item>
      <el-form-item label="帖子类型" prop="postType">
        <el-select v-model="posts.postType" placeholder="请选择帖子类型">
          <el-option label="programmer" value="programmer" />
          <el-option label="task" value="task" />
          <el-option label="community" value="community" />
        </el-select>
      </el-form-item>
      <el-form-item label="帖子内容" prop="content">
        <el-input v-model="posts.content" type="textarea" placeholder="请输入帖子内容" />
      </el-form-item>
      <el-form-item label="可上传附件" prop="file">
                <el-upload class="upload-demo" drag
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple>
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">
                        可将附件拖拽到此处或<em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            jpg/png文件不能超过500kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
      <el-form-item style="margin-left: 320px;">
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </el-main>

  <el-footer>
    <div class="footer">
      <div>
        <a href="#">动态公告</a> |
        <a href="#">帮助</a> |
        <a href="#">关于我们</a> |
        <a href="#">合作伙伴</a> |
        <a href="#">意见反馈</a> |
        <text style="color: rgb(78, 77, 77);">@“码上有钱”程序员接单平台</text>
      </div>
      <div class="credits">粤ICP备20220901号-4 | 粤公网安备33011002011599号</div>
    </div>
  </el-footer>
</template>

<style scoped>
.el-menu--horizontal > .el-menu-item:nth-child(1) {
  margin-right: auto;
}

.footer {
  margin-top: 100px;
  padding: 10px 0;
  border-top: 1px solid #ddd;
  text-align: center;
}

.footer a {
  text-decoration: none;
  color: rgb(78, 77, 77);
  background: transparent;
  border: none;
  cursor: pointer;
}

.footer .credits {
  margin-top: 5px;
  font-size: 12px;
  color: gray;
}
</style>
